package com.lanchetech.merchant.config;


import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;

public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(
            Authentication auth, Object targetDomainObject, Object permission) {
        if ((auth == null) || (targetDomainObject == null) || !(permission instanceof String)) {
            return false;
        }
        // permission 由 RESOURCE_PERMISSION组成，例如 ADMIN_LIST_READ， ADMIN_LIST是资源，READ是权限
        // @PreAuthorize("hasPermission('admin_list', 'read')")
        // @PostAuthorize("hasPermission('admin_list', 'read')")
        return hasPrivilege(auth, targetDomainObject.toString(), permission.toString());
    }

    @Override
    public boolean hasPermission(
            Authentication auth, Serializable targetId, String targetType, Object permission) {
        return false;
    }

    private boolean hasPrivilege(Authentication auth, String resource, String permission) {
        for (GrantedAuthority grantedAuth : auth.getAuthorities()) {
            if (grantedAuth.getAuthority().startsWith(resource)) {
                if (grantedAuth.getAuthority().contains(permission)) {
                    return true;
                }
            }
        }
        return false;
    }
}
